package com.bianmaba.spring.security.database;

import com.bianmaba.spring.security.basic.BasicWebSecurityConfiguration;
import com.bianmaba.spring.security.basic.BasicWebSecurityConfigurerAdapter;
import com.bianmaba.spring.security.database.core.DefaultResourceDetailsService;
import com.bianmaba.spring.security.database.core.DefaultUserDetailsService;
import com.bianmaba.spring.security.database.core.IResourceDetailsService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.AuthenticationEntryPoint;

@ConditionalOnClass({EnableWebSecurity.class, AuthenticationEntryPoint.class})
@ConditionalOnWebApplication
@ConditionalOnMissingBean({WebSecurityConfiguration.class})
@EnableWebSecurity//开启时将会启动自定义配置，不再使用SpringBoot的自动配置
public class DatabasicWebSecurityConfiguration extends BasicWebSecurityConfiguration {
    @Bean
    @ConditionalOnMissingBean
    public BasicWebSecurityConfigurerAdapter basicWebSecurityConfigurerAdapter() {
        return new DatabaseWebSecurityCongigurerAdapter();
    }

    @Bean
    @ConditionalOnMissingBean
    public IResourceDetailsService resourceDetailsService() {
        return new DefaultResourceDetailsService();
    }


    @Bean
    @ConditionalOnMissingBean
    public UserDetailsService userDetailsService() {
        return new DefaultUserDetailsService();
    }


    @Bean
    @ConditionalOnMissingBean(DatabaseSecurityFilter.class)
    public DatabaseSecurityFilter databaseSecurityFilter() {
        return new DatabaseSecurityFilter(securityMetadataSource(), accessDecisionManager());
    }

    @Bean
    @ConditionalOnMissingBean
    public DatabaseSecurityMetadataSource securityMetadataSource() {
        return new DatabaseSecurityMetadataSource();
    }

    @Bean
    @ConditionalOnMissingBean
    public DatabaseAccessDecisionManager accessDecisionManager() {
        return new DatabaseAccessDecisionManager();
    }
}
